package org.custom.spring.boot.transaction.service.stream;

import cn.hutool.core.util.StrUtil;
import org.custom.spring.boot.transaction.entity.Transaction;
import org.custom.spring.boot.transaction.mapper.TransactionMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * StreamTractionService
 *
 * @author 李坤
 * @date 2022/3/20 17:13
 */
@Service
public class StreamTractionService {
    @Resource
    private TransactionMapper transactionMapper;

    @Transactional
    public void validated_ParallelStream_Transaction() {
        AtomicInteger atomicInteger = new AtomicInteger(0);

        this.obtainTransactions().parallelStream().forEach(transaction -> {
            int value;
            transactionMapper.insert(transaction);
            if ((value = atomicInteger.incrementAndGet()) % 2 == 0) {
                System.out.println(value);
                int s = value / 0;
            }
        });
    }

    private List<Transaction> obtainTransactions() {
        List<Transaction> accounts = new ArrayList<>();

        accounts.add(Transaction.getInstance(StrUtil.uuid()));
        accounts.add(Transaction.getInstance(StrUtil.uuid()));
        accounts.add(Transaction.getInstance(StrUtil.uuid()));
        accounts.add(Transaction.getInstance(StrUtil.uuid()));
        accounts.add(Transaction.getInstance(StrUtil.uuid()));

        return accounts;
    }
}
